package com.wenbo.fish.service.factory;

import com.wenbo.fish.enums.SpiderServiceEnum;
import com.wenbo.fish.service.SpiderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @author changwenbo
 * @date 2024/12/31 14:46
 */
@Slf4j
@Component
public class SpiderFactory {

    private Map<String, SpiderService> spiderServiceMap = new HashMap<>();

    @Autowired
    private ApplicationContext applicationContext;

    @PostConstruct
    public void init() {
        Map<String, SpiderService> beansOfType = applicationContext.getBeansOfType(SpiderService.class);
        if (CollectionUtils.isEmpty(beansOfType)) {
            return;
        }

        for (Map.Entry<String, SpiderService> entry : beansOfType.entrySet()) {
            SpiderService spiderService = entry.getValue();
            spiderServiceMap.put(spiderService.getServiceName().getName(), spiderService);
        }

        log.info("spiderService  map = {}", spiderServiceMap);
    }

    public SpiderService getSpiderService(SpiderServiceEnum serviceName) {
        return spiderServiceMap.get(serviceName.getName());
    }
}
